<?php
declare (strict_types = 0);
namespace app\controller;

use think\facade\View;
use think\facade\Db;
use think\Validate;
use think\facade\Request;
use think\facade\Session;
use app\model\GoodsModel;
use app\model\UserModel;
use app\model\DeptModel;
use app\model\CatModel;
use think\facade\Cache;
use app\Common;

//产品控制器
class Goods{

    //常用数据表内容 及常用字典
    var $goods=[];
    var $users =[];
    var $cats=[];
    var $status=array('1'=>'上架','2'=>'下架','3'=>'作废');
    var $back = "<script>setTimeout(function(){history.back();},3000)</script>";

    public function __construct(){
        $gm=new GoodsModel();
        $this->goods = $gm->getAll();
        $um=new UserModel();

        $list = Db::table("user")->select()->toArray();
        foreach($list as $k=>$v){
            $this->users[$v['id']]=$v;
        }

        $cm=new CatModel();
        $this->cats = $cm->catTree();

        $sys=Db::table('sys')->find(1);
        $tdk=  explode("----",$sys['tdk']);
        $sys['tdk1']=!empty($tdk[0])?$tdk[0]:'导航首页';
        $sys['tdk2']=!empty($tdk[0])?$tdk[1]:'网站导航';
        $sys['tdk3']=!empty($tdk[0])?$tdk[2]:'网站,导航,信息,软件';
        $this->sys=$sys;
        unset($sys);

    }

    public function getImgs($imgs=''){
        if(!$imgs) return '';
        $arr = explode(",",$imgs);
        return implode(",",$arr);
    }

    //商品主页
    public function index($page=1){
        $uid=Session::get('logonid');
        if(!$uid) return header('location:/index.php/login');
        $user=Db::table('user')->find($uid);

        $goods = new GoodsModel();
        $all = Request::param();
        $list = Db::table('goods');

        if($user['group_id'] !=1){
            $list->whereRaw("ISNULL(user_id) or user_id='' or user_id=".$uid);
        }

        $query_arr=array(); 

        //名称查询
        // $name ='';
        // if(!empty($all['name'])){
        //     $name = $all['name'];
        //     $list = $list->where('name','like','%'.$name.'%');
        // }
        
        //商品类别查询
        $cat_id='';
        if(!empty($all['cat_id'])){
            $cat_id=$all['cat_id'];
            $cat_ct = new Cat();
            $sub_cats =[$cat_id];
            $sub_cats = $cat_ct->getSubCats($cat_id,$sub_cats);
            $list->where('cat_id','in',$sub_cats);
            //dump($cat_id,$sub_cats);
        }

        $status='';
        if(!empty($all['status'])){
            if($all['status']=='blank'){
                $list->whereRaw("ISNULL(user_id) or user_id=''");
            }
            if($all['status']=='mine'){
                $list->where('user_id',$uid);
                $status='mine';
            }
        }

        if(!empty($all['view_type'])){
            $this->sys['view_type']=$all['view_type'];
            $paginate=50;
        }else{
            $this->sys['view_type']='list';
            $paginate=15;
        }
        
        $list = $list->order('cat_id,id')->paginate($paginate)->toArray();

        foreach($list['data'] as &$v){
            $v['user_id_name']='';
            if($v['user_id']){
                $v['user_id_name'] = Db::table('user')->where('id',$v['user_id'])->value('name');
            }
            $v['status_name']=$this->status[$v['status']];
            $v['cat_id_name']=$this->cats[$v['cat_id']]['name'];

            $v['expire']=0;
            if($v['user_id'] && $v['end_time']<date('Y-m-d')){
                $v['expire']=1;
            }

            $v['image']=explode(",",$v['image']);
            $tmp=[];
            foreach($v['image'] as &$img){
                if(!$img) continue;
                if($img && substr($img,0,4)!='http'){
                    $tmp[]="http://".$_SERVER['HTTP_HOST'].$img;
                }
            }

            $v['image']=$tmp;

        }

        //处理分页其它参数
        //if($dept_id) $query_arr['dept_id']=$dept_id;
        if($cat_id) $query_arr['cat_id']=$cat_id;
        $query="&".http_build_query($query_arr);

        View::assign([
            'list'=>$list,
            //'name'=>$name,
            'cats'=>$this->cats,
            'cat_id'=>$cat_id,
            'user'=>$user,
            'query'=>$query,
            'status'=>$status,
            'sys'=>$this->sys,
            ]);
        return View::fetch();

    }


    public function detail(){
        $uid=Session::get('logonid');
        if(!$uid) return header('location:/index.php/login');

        $all = Request::param();
        if(empty($all['id'])) return Common::error('Invalid id!').$this->back ;

        $row=Db::table('goods')->find($all['id']);
        $arr = explode(',',$row['image']);
        if(count($arr)>2){
            unset($arr[0]);
            unset($arr[1]);
        }else{
            return Common::error('没有其它详细资料!').$this->back;
        }

        View::assign(['dt_imgs'=>$arr,'sys'=>$this->sys]);
        return View::fetch();
    }


    //产品编辑方法
    public function edit(){
        $uid=Session::get('logonid');
        if(!$uid) return header('location:/index.php/login');

        $all = Request::param();
        if(empty($all['id'])) return 'Invalid item id!'.$this->back ;

        $goods = new GoodsModel();

        //提交内容
        if($all['id']>0 && !empty($all['post'])){


            if(!empty($all['name'])){
                if(strlen($all['name'])>10){
                    return '名称超过10个字！'.$this->back;
                }

                $ex = Db::query("select * from goods where id<>? and name=?",array($all['id'],$all['name']));
                if(count($ex)) {
                    return '名称重复!'.$this->back;
                }
            }

            $all['create_time'] = date('Y-m-d H:i:s'); 

            $row=Db::table('goods')->find($all['id']);
            if(!empty($all['status']) && $row['status'] != $all['status']){
                if($all['status']!=1){//下架

                    $img=public_path().explode(",",$row['image'])[0];
                    if(is_file($img)){
                        rename($img,$img."__bak");
                    }
                    $all['image_bak']=$row['image'];
                    $all['image']='/upload/close.jpg';

                }else{
                    $img_bak=public_path().explode(",",$row['image_bak'])[0]."__bak";
                    if(is_file($img_bak)){
                        $img=str_replace("__bak",'',$img_bak);
                        rename($img_bak,$img);
                    }
                    $all['image']=$row['image_bak'];
                    $all['image_bak']='';
                }
            }

            Db::table('goods')->save($all);
            return header('location:/goods/index');
        }

        //不传内容只有id,查出本条数据 并进入编辑
        $row = $goods->find($all['id']);
        $row['image']=explode(",",$row['image']);
        $row['dt_imgs']=explode(",",$row['dt_imgs']);

        View::assign(['data'=>$row,'cats'=>$this->cats,'user'=>$this->users[$uid]]);

        return View::fetch();
    }

    //从一个表里查询出一条数据
    public function getOne($id,$table='goods'){
        $row = Db::table($table)->find($id);
        if($row){
            return $row;
        }else{
            return [];
        }
    }

    //保存一条数据
    public function save($table='goods'){
        $all = Request::param();
        if(!$all) return 'Invalid request!'.$this->back ;

        $res = Db::table($table)->save($all);
        return $res;
    }


    //加一张图
    public function add_image(){
        $all = Request::param();
        if(!$_FILES) return 'Error!';

        if(empty($all['tb']) || empty($all['field']) || empty($all['row_id'])) return 'Error!';

        foreach($_FILES as $file){
            if($file['size']>0){
                $files =Common::upload($file);
                
                if($files['code']){
                    $row=Db::table($all['tb'])->where('id',$all['row_id'])->find();
                    if($row[$all['field']]!='') {
                        $image= $row[$all['field']].$files['msg'];
                    }else{
                        $image=$files['msg'];
                    }
                    $res = Db::table($all['tb'])->update(['id'=>$row['id'],$all['field']=>$image]);
                    return json(['code'=>$res,'msg'=>'ok']);
                }else{
                    return json(['code'=>0,'msg'=>$files['msg']]);
                }
            }
        }
    }


    public function goods_add(){
        $uid=Session::get('logonid');
        if(!$uid) return header('location:/index.php/login');

        $all = Request::param();
        if($all){
            if(!empty($all['id'])) return '不是一个新的!'.$this->back;     
            if(!$all['name']) return '无效的名称!'.$this->back;

            $goods = new GoodsModel();
            $row = $goods::where('name',trim($all['name']))->find();
            if(!empty($row)) return '名称已存在! ['. $all['name']."]".$this->back;

            $all['creater']  = $uid;
            $all['create_time']  = date("Y-m-d H:i:s",time());
            $all['dept_id'] = 1;

            $new_id = $goods->insertGetId($all);
            return header("location:/goods/index");
        }

        View::assign(['cats'=>$this->cats]);
        return View::fetch();
    }

    public function goods_del(){
        $uid = Session::get('logonid');
        if(!$uid) return header('location:/index.php/login/target/admin');

        $all = Request::param();
        //halt($all);
        if($all){
            return Common::row_del('goods',$all['id'],'商品');
        }
        return json(['code'=>0]);
    }

    public function click(){
        header('Access-Control-Allow-Origin:*');  
        header('Access-Control-Allow-Methods:POST,GET');  
        header('Access-Control-Allow-Headers:x-requested-with,content-type');  //表示只允许x-requested-with和content-type的请求头访问

        $all=Request::param();
        if(empty($all['gid'])){
            return json(['code'=>0,'msg'=>'缺少商品id参数！']);
        }
        Db::execute('update goods set click=click+1 where id=?',[$all['gid']]);

        return json(['code'=>1,'msg'=>'+1']);
    }


    public function ad_clean(){
        $all=Request::param();
        if(empty($all['id'])){
            return '缺少id！'.$this->back;
        }
        $row=array(
            'id'=>$all['id'],
            'user_id'=>null,
            'order_id'=>null,
            'link_url'=>'',
            'image'=>'',
            'text'=>'',
            'start_time'=>'',
            'end_time'=>''
        );

        $res= Db::table('goods')->save($row);

        return json(['code'=>1,'msg'=>'回收完成...']);
    }


    public function batch_script(){
        $all=Request::param();
        $uid = Session::get('logonid');
        if(empty($all['ids']) || !count($all['ids'])){
            return json(['code'=>0,'msg'=>'请选择广告！']);
        }

        $ids = implode(",",$all['ids']);
        $arr=Db::table('goods')->whereIn('id',$all['ids'])->select();
                    
        $ad_str = $this->get_ad_str1('ad-box');

        foreach($arr as $goods){
            $item_str= $this->get_ad_item($goods);
            $ad_str .=$item_str;
        }
        $ad_str .= $this->get_ad_str2();

        if(!is_dir('ad_script')) mkdir('ad_script', 0777, true);
        $scrpit_name = "ad_script/g_batch_".($uid*31+9).".js";
        $ok = file_put_contents($scrpit_name,$ad_str);

        if($ok){
            $full_name = '<div id="ad-box"></div><script src="//'.$_SERVER['SERVER_NAME'].'/'.$scrpit_name.'?v='.time().'"></script>';
            return json(['code'=>1,'msg'=>$full_name]);
        }else{
            return json(['code'=>0,'msg'=>'Error!']);
        }

    }

    public function ad_script(){
        $all=Request::param();
        if(empty($all['id'])){
            return json(['code'=>0,'msg'=>'请选择广告！']);
        }

        $goods=Db::table('goods')->find($all['id']);


        $ad_str = $this->get_ad_str1('ad_'.$goods['id']);
        $ad_str .= $this->get_ad_item($goods);
        $ad_str .= $this->get_ad_str2();


        if(!is_dir('ad_script')) mkdir('ad_script', 0777, true);

        $scrpit_name = "ad_script/g".($goods['id']*31+3).".js";
        $ok = file_put_contents($scrpit_name,$ad_str);
        
        if($ok){
            $full_name = '<div id="ad_'.$goods['id'].'"></div><script src="//'.$_SERVER['SERVER_NAME']."/".$scrpit_name.'?v='.time().'"></script>';
            $res = Db::execute('update goods set ad_js=? where id=?',[$full_name,$goods['id']]);
            return json(['code'=>1,'js'=>$full_name]);
        }

    }


    function get_ad_str1($container_id){
        return "
        document.addEventListener('DOMContentLoaded', function () {
          //create a container for ad items
          var adc = document.getElementById('".$container_id."');
          adc.style.position='relative';
          adc.style.zIndex='10000';
          adc.style.overflow='hidden';
          ";
    }

    function get_ad_str2(){
        return "});";
    }

    function get_ad_item($goods){
        $server=$_SERVER['SERVER_NAME'];
        if($goods['status']!=1) return "";

        $item_str = "
            //create a div element for ad item
            var edate='".strtotime($goods['end_time'])."';
            var now = Date.now()/1000;
            //console.log('Expire time:'+edate,'Time:'+now,'Expired:'+now>edate);

            var ad_item= document.createElement('div');
            ad_item.style.position='relative';
            ad_item.style.width='image_width';
            ad_item.style.border = '1px solid #ccc';
            ad_item.style.textAlign = 'center';

            //expired checking
            if(now<edate){
                ad_item.addEventListener('click',function(event){
                    var xhr = new XMLHttpRequest();
                    xhr.open('POST', '//".$_SERVER['SERVER_NAME']."/goods/click/gid/".$goods['id']."', true);
                    xhr.onload = function() {
                      if (xhr.status >= 200 && xhr.status < 300) {
                        var data = JSON.parse(xhr.responseText);
                        window.open('link_url','_blank');
                      } else {
                        alert('Request failed:', xhr.statusText);
                      }
                    };
                    xhr.onerror = function() {
                      console.error('Network error!');
                    };
                    xhr.send();
                });
            }else{
                ad_item.addEventListener('click',function(event){
                    alert('Ad expired!');
                });
            }
            adc.appendChild(ad_item);
            ";

        if($goods['image']){
            $item_str.="
            //image in ad item
            var adimg = document.createElement('img');
            adimg.style.width = '100%';
            adimg.style.height = 'auto';
            adimg.style.cursor = 'pointer';            
            if(now<edate){
                adimg.src = 'image_source'; 
            }else{
                adimg.src = '//".$_SERVER['SERVER_NAME']."/upload/ad_expired.jpg';
            }
            ad_item.appendChild(adimg);
            ";
        }else{
            $item_str.="
            if(now<edate){
                ad_item.innerText='".$goods['text']."';
            }else{
                ad_item.innerText='广告已过期!';
            }";
        }
            
        $item_str.="
            //close button
            var adt1 = document.createElement('img');
            adt1.style.position='absolute';
            adt1.style.zIndex='10001';
            adt1.style.right='1px';
            adt1.style.bottom='1px';
            adt1.style.cursor='pointer';
            adt1.src='//".$server."/upload/ad_close.png';
            adt1.addEventListener('click', function(event) {
                event.stopPropagation();
                var pe = this.parentElement;
                pe.style.display='none';
            });
            ad_item.appendChild(adt1);

            //prompt text for ad item 
            var adt2 = document.createElement('img');
            adt2.style.position='absolute';
            adt2.style.zIndex='10001';
            adt2.style.right='13px';
            adt2.style.bottom='1px';
            adt2.src='//".$server."/upload/ad_tag.png';
            ad_item.appendChild(adt2);
            ";

        $item_str = str_replace("link_url",$goods['link_url'],$item_str);
        
        $img=explode(",",$goods['image']);
        if(!count($img)) json(['code'=>0,'msg'=>'缺少图片！']);

        if($goods['image_width']){
            $item_str=str_replace("'image_width'","'".$goods['image_width']."'",$item_str);
        }else{
            $item_str=str_replace("'image_width'","'100%'",$item_str);
        }

        $item_str=str_replace("image_source",'//'.$_SERVER['SERVER_NAME'].$img[0],$item_str); 

        return $item_str;         
    }




}